/**
 * Created by jiadx on 2016/3/18.
 */
'use strict';

angular.module('Query')
    .controller('SingleProductStreamController', ['$scope', '$http', '$q', '$stateParams', '$timeout', 'BaseModule', 'BaseEnum', 'usbPort', 'BaseFunction',
        function($scope, $http, $q, $stateParams, $timeout, BaseModule, BaseEnum, usbPort, BaseFunction) {
            BaseModule.initModule($scope, 'BarcodeMaster');

            $scope.data = {
                bizCatalog: [],
                bizRecords: {
                    record: []
                },
                Barcode: '',
                productParam: {},
                icon_position: {}
            };

            $scope.unfold = function(index) {
                var h = 0;
                for (var i = 0; i < index; i++) {
                    h += (angular.element('.list-exp_' + i).outerHeight() - 34);
                }
                angular.element('.query-context').scrollTop(h);
            };

            $scope.$on('usbPort.input', function(e, inputStr) {
                getData(inputStr);
            });

            $scope.$on('$destroy', function() {
                usbPort.stop();
            });

            function queryProduct(Barcode) {
                var defer = $q.defer();
                $http({
                    method: 'POST',
                    url: 'api/ProductFlow/getProductFlow',
                    data: {
                        Parameter: {
                            Barcode: Barcode
                        }
                    }
                }).success(function(result) {
                    defer.resolve(result);
                }).error(function(error) {
                    defer.reject(error);
                });

                return defer.promise;
            }

            $scope.search = function(records) {
                if(records.length !== 0){
                    getData(records[0].Barcode);
                }
            };

            $scope.init = function() {
                if ($stateParams.Barcode && $stateParams.Barcode !== '') {
                    getData($stateParams.Barcode);
                }

                usbPort.start();
            };
            $scope.init();

            function dateFormat(dateStr, fmt) { //author: meizz
                var date = new Date(dateStr);
                var o = {
                    "M+": date.getMonth() + 1, //月份
                    "d+": date.getDate(), //日
                    "h+": date.getHours(), //小时
                    "m+": date.getMinutes(), //分
                    "s+": date.getSeconds(), //秒
                    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
                    "S": date.getMilliseconds() //毫秒
                };
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
                }
                for (var k in o) {
                    if (new RegExp("(" + k + ")").test(fmt)) {
                        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                    }
                }
                return fmt;
            }

            function getData(barcode) {
                queryProduct(barcode).then(function(strr) {
                        if (!strr) {
                            BaseFunction.tip("", "没有对应的流水信息");
                            return;
                        }
                        if (!strr.Data) {
                            BaseFunction.tip("", "没有对应的流水信息");
                            return;
                        }
                        angular.forEach(strr.Data.bizCatalog, function(value) {
                            value.record = strr.Data.bizRecords[value.UniqueId];
                            angular.forEach(value.record, function(rec) {
                                var uString = '';
                                angular.forEach(rec.Users, function(u) {
                                    uString = uString + u.Name + ' ';
                                });
                                rec.Users = [{
                                    Name: uString
                                }];
                                rec.CollectDateTime = dateFormat(rec.CollectDateTime, "yyyy-MM-dd hh:mm:ss");
                                var h = 0,
                                    m = 0,
                                    s = 0;
                                if (rec.WorkTime) {
                                    h = Math.floor(rec.WorkTime / 3600);
                                    m = Math.floor((rec.WorkTime - h * 3600) / 60);
                                    s = rec.WorkTime - h * 3600 - m * 60;
                                    rec.WorkTime = h + ':' + m + ':' + Math.round(s);
                                }
                            });
                        });
                        $scope.Module.BarcodeMaster.FocusedRecord = {};
                        $scope.Module.BarcodeMaster.FocusedRecord.BarcodeMaster = {
                            Barcode: barcode
                        };
                        
                        if (strr.Data.basicInfo.StartDateTime) {
                            strr.Data.basicInfo.StartDateTime = dateFormat(strr.Data.basicInfo.StartDateTime, "yyyy-MM-dd");
                        }

                        if (strr.Data.basicInfo.RealStartDateTime) {
                            strr.Data.basicInfo.RealStartDateTime = dateFormat(strr.Data.basicInfo.RealStartDateTime, "yyyy-MM-dd");
                        }
                        if (strr.Data.basicInfo.EndDateTime) {
                            strr.Data.basicInfo.EndDateTime = dateFormat(strr.Data.basicInfo.EndDateTime, "yyyy-MM-dd");
                        }

                        if (strr.Data.basicInfo.RealEndDateTime) {
                            strr.Data.basicInfo.RealEndDateTime = dateFormat(strr.Data.basicInfo.RealEndDateTime, "yyyy-MM-dd");
                        }

                        strr.Data.productParam.DescSeg3 = (strr.Data.productParam.DescSeg3 == "1" ? '是' : '否');

                        $scope.data = {
                            basicInfo: strr.Data.basicInfo,
                            bizCatalog: strr.Data.bizCatalog,
                            bizRecords: strr.Data.bizRecords,
                            productParam: strr.Data.productParam
                        };
                    },
                    function() {

                    });
            }
        }
    ])
